<template>
	<div class="flex h-screen bg-gray-50 overflow-hidden flex-col">
		<!-- 顶部导航 -->
		<nav class="h-24 bg-white shadow-sm fixed w-full z-50 flex items-center justify-between px-8">
			<div class="flex items-center gap-8">
				<!-- 系统Logo -->
				<div class="flex items-center gap-4 bg-slate-800 px-5 py-3 rounded-lg">
					<div class="logo-icon w-12 h-12">
						<svg viewBox="0 0 100 100" fill="none">
							<circle cx="50" cy="50" r="45" stroke="url(#gradient1)" stroke-width="3" fill="none" />
							<circle cx="50" cy="50" r="35" stroke="url(#gradient2)" stroke-width="2" fill="none" />
							<path d="M30 40 L50 30 L70 40 L70 60 L50 70 L30 60 Z" fill="url(#gradient3)"
								opacity="0.8" />
							<circle cx="50" cy="50" r="8" fill="white" />
							<defs>
								<linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="100%">
									<stop offset="0%" style="stop-color:#4A90E2" />
									<stop offset="100%" style="stop-color:#7BB3F0" />
								</linearGradient>
								<linearGradient id="gradient2" x1="0%" y1="0%" x2="100%" y2="100%">
									<stop offset="0%" style="stop-color:#5BA0F2" />
									<stop offset="100%" style="stop-color:#8CC8FF" />
								</linearGradient>
								<linearGradient id="gradient3" x1="0%" y1="0%" x2="100%" y2="100%">
									<stop offset="0%" style="stop-color:#4A90E2" />
									<stop offset="100%" style="stop-color:#6BB0FF" />
								</linearGradient>
							</defs>
						</svg>
					</div>
					<div class="flex flex-col">
						<span class="text-xl font-bold text-blue-600">
							EduLiveLink管理系统
						</span>
						<span class="text-xs text-black">
							智能教育平台
						</span>
					</div>
				</div>
			</div>
			<div class="flex items-center gap-4">
				<button
					class="bg-blue-600 text-white px-6 py-2 rounded-md font-medium hover:bg-blue-700 transition-colors"
					@click="goHome">返回首页</button>
			</div>
		</nav>

		<!-- 上方空白区域 -->
		<div class="h-24 bg-white"></div>

		<!-- 主要内容区域 -->
		<div class="flex flex-1 overflow-hidden">
			<!-- 侧边栏 -->
			<aside
				class="w-64 bg-white shadow-sm border-r border-gray-200 fixed h-[calc(100vh-6rem)] z-40 overflow-y-auto">
				<div class="p-6">
					<h2 class="text-lg font-semibold text-gray-900 mb-6">控制台导航</h2>
					<ul class="space-y-1">
						<li>
							<router-link to="/console"
								class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
								:class="currentPath === '/console' ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
								<span class="w-5 h-5 flex items-center justify-center">
									<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
										stroke-width="2">
										<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
										<polyline points="9 22 9 12 15 12 15 22"></polyline>
									</svg>
								</span>
								<span>控制台首页</span>
							</router-link>
						</li>
						<li>
							<router-link to="/console/usermanagement"
								class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
								:class="currentPath.startsWith('/console/usermanagement') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
								<span class="w-5 h-5 flex items-center justify-center">
									<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
										stroke-width="2">
										<path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
										<circle cx="8.5" cy="7" r="4"></circle>
										<line x1="20" y1="8" x2="20" y2="14"></line>
										<line x1="23" y1="11" x2="17" y2="11"></line>
									</svg>
								</span>
								<span>用户管理</span>
							</router-link>
						</li>
						<li>
							<router-link to="/console/classmanagement"
								class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
								:class="currentPath.startsWith('/console/classmanagement') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
								<span class="w-5 h-5 flex items-center justify-center">
									<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
										stroke-width="2">
										<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
										<polyline points="9 22 9 12 15 12 15 22"></polyline>
									</svg>
								</span>
								<span>班级管理</span>
							</router-link>
						</li>
						<li>
						  <router-link to="/console/coursemanagement"
						    class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
						    :class="currentPath.startsWith('/console/coursemanagement') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
						    <span class="w-5 h-5 flex items-center justify-center">
						      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
						        <path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path>
						        <path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path>
						      </svg>
						    </span>
						    <span>课程管理</span>
						  </router-link>
						</li>
						<li>
							<router-link to="/console/resources"
								class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
								:class="currentPath.startsWith('/console/resources') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
								<span class="w-5 h-5 flex items-center justify-center">
									<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
										stroke-width="2">
										<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
										<polyline points="14 2 14 8 20 8"></polyline>
										<line x1="16" y1="13" x2="8" y2="13"></line>
										<line x1="16" y1="17" x2="8" y2="17"></line>
										<polyline points="10 9 9 9 8 9"></polyline>
									</svg>
								</span>
								<span>资源管理</span>
							</router-link>
						</li>
						<li>
							<router-link to="/console/settings"
								class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
								:class="currentPath.startsWith('/console/settings') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
								<span class="w-5 h-5 flex items-center justify-center">
									<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
										stroke-width="2">
										<circle cx="12" cy="12" r="3"></circle>
										<path
											d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z">
										</path>
									</svg>
								</span>
								<span>系统设置</span>
							</router-link>
						</li>
					</ul>
				</div>
			</aside>

			<!-- 主内容区域 -->
			<div class="flex-1 flex flex-col overflow-hidden ml-64">

				<!-- 内容区域 -->
				<main class="flex-1 overflow-y-auto p-6">
					<div class="page-header">
						<h1 class="text-3xl font-bold text-gray-900 mb-2">班级管理</h1>
						<p class="page-description">管理平台所有班级信息，包括查看、编辑和删除班级</p>
					</div>
					<div class="h-12"></div>
					<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
						<!-- 搜索区域 -->
						<div class="p-4 border-b border-gray-200">
							<div class="flex flex-wrap gap-4">
								<el-input v-model="searchKeyword" placeholder="搜索班级名称或班级码" style="width: 300px"
									clearable @clear="handleSearch" @keyup.enter="handleSearch" />
								<el-select v-model="searchGrade" placeholder="选择年级" clearable @change="handleSearch">
									<el-option v-for="grade in gradeOptions" :key="grade.value" :label="grade.label"
										:value="grade.value" />
								</el-select>
								<el-button type="primary" @click="handleSearch">搜索</el-button>
								<el-button @click="resetSearch">重置</el-button>
							</div>
						</div>

						<!-- 表格区域 -->
						<div class="overflow-x-auto">
							<table class="w-full">
								<thead class="bg-gray-50">
									<tr>
										<th
											class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
											班级ID</th>
										<th
											class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
											班级名称</th>
										<th
											class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
											年级</th>
										<th
											class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
											班级简介</th>
										<th
											class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
											班级码</th>
										<th
											class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
											操作</th>
									</tr>
								</thead>
								<tbody class="bg-white divide-y divide-gray-200">
									<tr v-for="classItem in classList" :key="classItem.id" class="hover:bg-gray-50">
										<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ classItem.id }}
										</td>
										<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
											{{ classItem.name }}</td>
										<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
											{{ classItem.grade }}</td>
										<td class="px-6 py-4 text-sm text-gray-900 max-w-xs truncate">
											{{ classItem.description || '-' }}
										</td>
										<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
											<span
												class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
												{{ classItem.classCode }}
											</span>
										</td>
										<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
											<button class="text-blue-600 hover:text-blue-900 mr-4"
												@click="handleEdit(classItem)">
												编辑
											</button>
											<button class="text-red-600 hover:text-red-900"
												@click="handleDelete(classItem)">
												删除
											</button>
										</td>
									</tr>
									<tr v-if="classList.length === 0 && !loading">
										<td colspan="6" class="px-6 py-12 text-center text-gray-500">
											暂无班级数据
										</td>
									</tr>
									<tr v-if="loading">
										<td colspan="6" class="px-6 py-12 text-center text-gray-500">
											<el-loading-spinner></el-loading-spinner>
											<span class="ml-2">加载中...</span>
										</td>
									</tr>
								</tbody>
							</table>
						</div>

						<!-- 分页 -->
						<div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
							<div class="text-sm text-gray-700">
								共 {{ total }} 条记录
							</div>
							<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
								:page-sizes="[10, 20, 50]" :total="total" layout="prev, pager, next, sizes"
								@size-change="handleSizeChange" @current-change="handleCurrentChange" />
						</div>
					</div>
				</main>
			</div>

			<!-- 新增/编辑班级弹窗 -->
			<el-dialog v-model="showCreateDialog" :title="editingClass ? '编辑班级' : '新增班级'" width="600px">
				<el-form ref="classFormRef" :model="classForm" :rules="classFormRules" label-width="100px">
					<el-form-item label="班级名称" prop="name">
						<el-input v-model="classForm.name" placeholder="请输入班级名称" />
					</el-form-item>
					<el-form-item label="年级" prop="grade">
						<el-select v-model="classForm.grade" placeholder="请选择年级">
							<el-option v-for="grade in gradeOptions" :key="grade.value" :label="grade.label"
								:value="grade.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="班级简介" prop="description">
						<el-input v-model="classForm.description" type="textarea" :rows="4" placeholder="请输入班级简介" />
					</el-form-item>
					<el-form-item label="班级码" v-if="editingClass">
						<el-input v-model="classForm.classCode" disabled />
						<div class="text-xs text-gray-500 mt-1">班级码自动生成，不可修改</div>
					</el-form-item>
				</el-form>
				<template #footer>
					<el-button @click="showCreateDialog = false">取消</el-button>
					<el-button type="primary" @click="submitForm">确认</el-button>
				</template>
			</el-dialog>

			<!-- 删除确认弹窗 -->
			<el-dialog v-model="showDeleteDialog" title="确认删除" width="400px">
				<p>确定要删除班级 "{{ deletingClass?.name }}" 吗？此操作不可恢复。</p>
				<template #footer>
					<el-button @click="showDeleteDialog = false">取消</el-button>
					<el-button type="danger" @click="confirmDelete">删除</el-button>
				</template>
			</el-dialog>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		ElMessage,
		ElLoading
	} from 'element-plus'
	import axios from 'axios'

	// 配置axios基础路径
	axios.defaults.baseURL = 'http://localhost:9010'

	// 路由相关
	const route = useRoute()
	const router = useRouter()
	const currentPath = computed(() => route.path)

	// 返回首页方法
	const goHome = () => {
		router.push('/')
	}

	// 响应式数据
	const classList = ref([])
	const total = ref(0)
	const currentPage = ref(1)
	const pageSize = ref(10)
	const searchKeyword = ref('')
	const searchGrade = ref('')
	const loading = ref(false)

	// 弹窗相关
	const showCreateDialog = ref(false)
	const showDeleteDialog = ref(false)
	const editingClass = ref(null)
	const deletingClass = ref(null)
	const classFormRef = ref(null)

	// 年级选项
	const gradeOptions = [{
			value: '一年级',
			label: '一年级'
		},
		{
			value: '二年级',
			label: '二年级'
		},
		{
			value: '三年级',
			label: '三年级'
		},
		{
			value: '四年级',
			label: '四年级'
		},
		{
			value: '五年级',
			label: '五年级'
		},
		{
			value: '六年级',
			label: '六年级'
		},
		{
			value: '初一',
			label: '初一'
		},
		{
			value: '初二',
			label: '初二'
		},
		{
			value: '初三',
			label: '初三'
		},
		{
			value: '高一',
			label: '高一'
		},
		{
			value: '高二',
			label: '高二'
		},
		{
			value: '高三',
			label: '高三'
		}
	]

	// 表单数据
	const classForm = reactive({
		id: '',
		name: '',
		grade: '',
		description: '',
		classCode: ''
	})

	// 表单验证规则
	const classFormRules = {
		name: [{
				required: true,
				message: '请输入班级名称',
				trigger: 'blur'
			},
			{
				max: 50,
				message: '班级名称不能超过50个字符',
				trigger: 'blur'
			}
		],
		grade: [{
			required: true,
			message: '请选择年级',
			trigger: 'change'
		}]
	}

	// 页面加载时获取班级列表
	onMounted(() => {
		fetchClassList()
	})

	// 获取班级列表
	const fetchClassList = async () => {
	  try {
	    loading.value = true
	    const params = {
	      keyword: searchKeyword.value,
	      grade: searchGrade.value,
	      pageNum: currentPage.value,
	      pageSize: pageSize.value
	    }
	    
	    const response = await axios.post('/api/class/list', params)
	    
	    if (response.data.code === 0) {
	      classList.value = response.data.data.list
	      total.value = response.data.data.total
	    } else {
	      ElMessage.error(response.data.msg || '获取班级列表失败')
	    }
	  } catch (error) {
	    console.error('获取班级列表失败:', error)
	    if (error.code === 'ERR_NETWORK') {
	      ElMessage.error('无法连接到服务器，请检查后端服务是否启动')
	    } else {
	      ElMessage.error('获取班级列表失败，请稍后重试')
	    }
	  } finally {
	    loading.value = false
	  }
	}
	
	// 提交表单
	const submitForm = async () => {
	  if (!classFormRef.value) return
	
	  try {
	    await classFormRef.value.validate()
	    
	    // 显示加载状态
	    const loadingInstance = ElLoading.service({
	      text: '处理中...'
	    })
	
	    if (editingClass.value) {
	      // 编辑班级逻辑
	      const response = await axios.post('/api/class/update', classForm)
	      
	      if (response.data.code === 0) {
	        ElMessage.success('班级更新成功')
	        showCreateDialog.value = false
	        fetchClassList() // 重新加载列表
	      } else {
	        ElMessage.error(response.data.msg || '班级更新失败')
	      }
	    }
	
	    resetForm()
	  } catch (error) {
	    if (error.response) {
	      ElMessage.error(error.response.data.msg || '操作失败')
	    } else if (error.name !== 'Error') {
	      // 表单验证失败不显示错误消息
	    } else {
	      ElMessage.error('操作失败，请稍后重试')
	    }
	  } finally {
	    ElLoading.service().close()
	  }
	}
	
	// 确认删除
	const confirmDelete = async () => {
	  if (!deletingClass.value) return
	
	  try {
	    // 显示加载状态
	    const loadingInstance = ElLoading.service({
	      text: '删除中...'
	    })
	
	    const params = { id: deletingClass.value.id }
	    const response = await axios.post('/api/class/delete', params)
	    
	    if (response.data.code === 0) {
	      ElMessage.success('班级删除成功')
	      showDeleteDialog.value = false
	      fetchClassList() // 重新加载列表
	    } else {
	      ElMessage.error(response.data.msg || '班级删除失败')
	    }
	  } catch (error) {
	    console.error('删除班级失败:', error)
	    ElMessage.error(error.response?.data?.msg || '班级删除失败，请稍后重试')
	  } finally {
	    ElLoading.service().close()
	  }
	}

	// 搜索处理
	const handleSearch = () => {
		currentPage.value = 1
		fetchClassList()
	}

	// 重置搜索
	const resetSearch = () => {
		searchKeyword.value = ''
		searchGrade.value = ''
		currentPage.value = 1
		fetchClassList()
	}

	// 分页大小变化
	const handleSizeChange = (size) => {
		pageSize.value = size
		currentPage.value = 1
		fetchClassList()
	}

	// 页码变化
	const handleCurrentChange = (page) => {
		currentPage.value = page
		fetchClassList()
	}

	// 编辑班级
	const handleEdit = (item) => {
		editingClass.value = { ...item }
		Object.assign(classForm, {
			id: item.id,
			name: item.name,
			grade: item.grade,
			description: item.description,
			classCode: item.classCode
		})
		showCreateDialog.value = true
	}

	// 删除班级
	const handleDelete = (item) => {
		deletingClass.value = item
		showDeleteDialog.value = true
	}

	// 重置表单
	const resetForm = () => {
		editingClass.value = null
		Object.assign(classForm, {
			id: '',
			name: '',
			grade: '',
			description: '',
			classCode: ''
		})
		if (classFormRef.value) {
			classFormRef.value.resetFields()
		}
	}
</script>

<style scoped>
	button {
		border: none;
		background: none;
		cursor: pointer;
		padding: 2px 4px;
	}
</style>
